package com.moss.cloud.common.security.interceptor;

import com.moss.cloud.auth.api.utils.JwtAccessToken;
import com.moss.cloud.common.core.constant.Constant;
import com.moss.cloud.common.core.model.vo.AuthUser;
import com.moss.cloud.common.core.utils.AuthUserUtil;
import com.moss.cloud.common.core.utils.UserContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;

/**
 * 用户信息拦截器
 *
 * @author 瑾年
 * @date 2023年3月14日
 */
@Slf4j
public class UserInterceptor implements HandlerInterceptor {
    /**
     * 服务间调用token用户信息,格式为json
     * {
     * "user_name":"必须有"
     * "自定义key:"value"
     * }
     */
    public static final String X_CLIENT_TOKEN_USER = "x-client-token-user";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        //String userInfoString = StringUtils.defaultIfBlank(request.getHeader(X_CLIENT_TOKEN_USER), Constant.NO_LOGIN);
        String userInfoString = Optional.ofNullable(request.getHeader(X_CLIENT_TOKEN_USER)).filter(StringUtils::isNotBlank)
                .orElseGet(() -> Optional.ofNullable(request.getHeader(HttpHeaders.AUTHORIZATION))
                        .filter(StringUtils::isNotBlank).orElse(Constant.NO_LOGIN));
        log.info("原始认证用户信息:{}", userInfoString);
        if (StringUtils.isNotEmpty(userInfoString) && !userInfoString.equals(Constant.NO_LOGIN)) {
            AuthUser authUser = AuthUserUtil.preAuthUser(userInfoString);
            log.info("当前登录用户:{}", authUser.getUserName());
            UserContextHolder.setUserInfo(authUser);
        } else {
            AuthUser authUser = AuthUserUtil.preAuthUser();
            log.info("用户未认证状态:{}", authUser.getAuthStatus());
            UserContextHolder.setUserInfo(authUser);
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) {
        UserContextHolder.clear();
    }
}
